import { defineStore } from 'pinia';
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
// import { menuTree } from '@/api/userCenter';
import { asyncRouterMap, constRouterMap } from '@/router';
import { cloneDeep } from 'lodash';
import config from '@/config';
//  方法
import { isEmpty } from '@/utils/tools';

// 前端路由树转成一维数组
function localTreeForeach(tree, obj = {}) {
  tree.forEach(item => {
    const i = Object.assign({}, item);
    // delete i.children;
    obj[item.name] = i;
    if (item && item.children && item.children.length > 0) {
      localTreeForeach(item.children, obj);
    }
  });
  return obj;
}

function findRoutePower(data = [], operationPermissions = {}) {
  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    if (item.routerName) {
      if (item.operationPermissions) {
        operationPermissions[item.routerName] = item.operationPermissions.filter(t => t.granted);
      }
    }
    if (item.children) {
      findRoutePower(item.children, operationPermissions);
    }
  }
  return operationPermissions;
}

// 递归后端返回路由树和前端路由匹配，合并所需参数，返回过滤后的路由树。
function resetTreeData(treeData, routerList) {
  let resultTree = [];
  treeData.forEach(item => {
    const obj = routerList[item.routerName] || {};
    let curComponent = {
      path: obj['path'] || item.routerName,
      name: obj['name'] || item.routerName,
      hideChildrenInMenu: obj['hideChildrenInMenu'],
      component: obj['component'],
      permission: obj['permission'],
      redirect: obj['redirect'],
      // operationPermissions: item['operationPermissions'],
      operationPermissions: item.operationPermissions,
      hidden: !item.isMenu,
      meta: {
        ...(obj?.meta || {}),
        // keepAlive: obj?.meta?.['keepAlive'],
        // toRoute: obj?.meta?.['toRoute'],
        title: item.name,
        hidden: !item.isMenu,
        // icon: item.icon,
        // iconHover: item.iconHover,
      },
    };

    if (!obj.hideChildrenInMenu && item.children && item.children.length) {
      curComponent.children = resetTreeData(item.children, routerList);
    } else if (obj.hideChildrenInMenu && obj['children']) {
      if (curComponent.operationPermissions && curComponent.operationPermissions.length) {
        curComponent.children = obj['children'].filter(comItem => {
          return curComponent.operationPermissions?.find(item => {
            return isEmpty(comItem.permission) || (item.granted && comItem['permission'].includes(item.permissionName));
          });
        });
      } else {
        curComponent.children = obj['children'];
      }
    }

    resultTree.push(curComponent);
  });

  return resultTree;
}

// 重置state函数
const getDefaultState = () => {
  return {
    curRoute: {},
    powers: {}, // 按钮权限
    addRouters: [],
    menuList: [],
  };
};

const defalutState = getDefaultState();

export const useStorePermission = defineStore('permission', () => {
  let state = reactive(defalutState);

  function GenerateRoutes() {
    const routerMap = cloneDeep(asyncRouterMap);
    return new Promise(resolve => {
      if (config.asyncRoutes) {
        menuTree().then(res => {
          let resultData = res.data;
          const obj = localTreeForeach(routerMap);
          const routerTree = resetTreeData(resultData, obj);
          const power = findRoutePower(resultData);
          const menuList = [...routerTree, ...constRouterMap];
          routerMap[0].children = menuList;
          state.addRouters = routerMap;
          state.powers = power;
          state.menuList = menuList;
          resolve(routerMap);
        });
      } else {
        routerMap[0].children = [...constRouterMap, ...routerMap[0].children];
        state.addRouters = routerMap;
        state.menuList = routerMap[0].children || [];
        resolve(routerMap);
      }
    });
  }

  // 修改state值
  const changeValue = (type, value) => {
    state[type] = value;
  };

  const resetValue = () => {
    Object.assign(state, getDefaultState());
  };

  return {
    GenerateRoutes,
    changeValue,
    resetValue,
    ...toRefs(state),
  };
});
